package com.renren.project.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.renren.project.db.bean.PageInfo;
import com.renren.project.db.bean.PageResult;
import com.renren.project.db.service.IBaseService;
import com.renren.project.db.utils.WrapperUtil;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName BaseServiceImpl
 * @Description Service实现类基类
 * @createTime 18:11:00 2021/08/02
 */
public class BaseServiceImpl <M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IBaseService<T> {

    public <V> PageResult<V> page(PageInfo pageInfo, Function<T, V> function) {
        return PageResult.result(page(getPage(pageInfo)), function);
    }

    public <V> PageResult<V> page(PageInfo pageInfo, Object cond, Function<T, V> function) {
        return PageResult.result(page(getPage(pageInfo), wrapper(cond)), function);
    }

    public <V> List<V> list(Function<T, V> function) {
        return list().stream().map(function).collect(Collectors.toList());
    }

    private Page<T> getPage(PageInfo pageInfo) {
        return Optional.ofNullable(pageInfo)
                .map(PageInfo::page)
                .orElse(PageInfo.maxSize().page());
    }

    private Wrapper<T> wrapper(Object cond) {
        if (cond instanceof Wrapper) {
            return (Wrapper<T>) cond;
        }
        return WrapperUtil.getWrapper(cond);
    }
}
